package com.zyf.ppx.download_utils

import android.content.Context
import android.os.Environment
import android.util.Log
import android.widget.Toast
import com.bumptech.glide.Glide
import com.zyf.ppx.bean.MuitImage
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException


object DownloadUtils {
    val path = Environment.getExternalStorageDirectory().absolutePath+"/ppx"
    private fun copy(source: File,  target:File){
        var fileInputStream: FileInputStream? = null
        var fileOutputStream: FileOutputStream? = null
        try {
            fileInputStream = FileInputStream(source)
            fileOutputStream = FileOutputStream(target)
            val buffer = ByteArray(1024)
            while (fileInputStream.read(buffer) > 0) {
                fileOutputStream.write(buffer)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            try {
                fileInputStream?.close()
                fileOutputStream?.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }

        }
    }
    fun download(imageData: MuitImage, context: Context){

        var target = if(imageData.is_gif){
            System.currentTimeMillis().toString() +".gif"
        }else{
            System.currentTimeMillis().toString() +".png"
        }
        Observable.just(target).map {
            var file = File(path)
            if(!file.exists()){
                file.mkdirs()
            }
            file = File(path+"/"+target)
            val files = Glide.with(context)
                .load(imageData.download_list[0].url)
                .downloadOnly(imageData.width, imageData.height)
                .get()
            copy(files, file)
            return@map target
        }.subscribeOn(Schedulers.io())
         .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                Log.e("path",it)
                Toast.makeText(context,"文件SD卡ppx/"+it,Toast.LENGTH_SHORT).show()
            },{
                Log.e("message",it.message)
            })
    }
}


